from rest_framework import serializers
from django.contrib.auth.models import User
from .models import DockerServer, DockerRegistry


class DockerServerSerializer(serializers.ModelSerializer):
    """Docker服务器序列化器"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)

    class Meta:
        model = DockerServer
        fields = [
            'id', 'name', 'description', 'host', 'ssh_port', 'ssh_username',
            'ssh_password', 'ssh_key_path', 'docker_port', 'use_ssh_tunnel',
            'is_active', 'is_default', 'connection_status', 'docker_version',
            'docker_api_version', 'system_info', 'total_containers',
            'running_containers', 'total_images', 'total_volumes',
            'total_networks', 'last_check_time', 'last_sync_time',
            'created_at', 'updated_at', 'created_by', 'created_by_name'
        ]
        extra_kwargs = {
            'ssh_password': {'write_only': True},  # 密码只写不读
            'created_by': {'read_only': True},
            'connection_status': {'read_only': True},
            'docker_version': {'read_only': True},
            'docker_api_version': {'read_only': True},
            'system_info': {'read_only': True},
            'total_containers': {'read_only': True},
            'running_containers': {'read_only': True},
            'total_images': {'read_only': True},
            'total_volumes': {'read_only': True},
            'total_networks': {'read_only': True},
            'last_check_time': {'read_only': True},
            'last_sync_time': {'read_only': True},
        }

    def create(self, validated_data):
        # 设置创建者
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class DockerServerListSerializer(serializers.ModelSerializer):
    """Docker服务器列表序列化器（不包含敏感信息）"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)

    class Meta:
        model = DockerServer
        fields = [
            'id', 'name', 'description', 'host', 'ssh_port', 'ssh_username',
            'is_active', 'is_default', 'connection_status', 'docker_version',
            'total_containers', 'running_containers', 'total_images',
            'last_check_time', 'created_at', 'created_by_name'
        ]


class DockerServerTestConnectionSerializer(serializers.Serializer):
    """Docker服务器连接测试序列化器"""
    host = serializers.CharField(max_length=255)
    ssh_port = serializers.IntegerField(default=22)
    ssh_username = serializers.CharField(max_length=100)
    ssh_password = serializers.CharField(max_length=255)
    ssh_key_path = serializers.CharField(max_length=500, required=False, allow_blank=True)


class DockerRegistrySerializer(serializers.ModelSerializer):
    """Docker镜像仓库序列化器"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)

    class Meta:
        model = DockerRegistry
        fields = [
            'id', 'name', 'url', 'registry_type', 'auth_type', 'username', 'password',
            'robot_token', 'email', 'is_active', 'is_default', 'auto_sync', 'connection_status',
            'repositories_count', 'last_sync_time', 'last_check_time',
            'created_at', 'updated_at', 'created_by', 'created_by_name'
        ]
        extra_kwargs = {
            'password': {'write_only': True},  # 密码只写不读
            'robot_token': {'write_only': True},  # Token只写不读
            'created_by': {'read_only': True},
            'connection_status': {'read_only': True},
            'repositories_count': {'read_only': True},
            'last_sync_time': {'read_only': True},
            'last_check_time': {'read_only': True},
        }

    def create(self, validated_data):
        # 设置创建者
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class DockerRegistryListSerializer(serializers.ModelSerializer):
    """Docker镜像仓库列表序列化器（不包含敏感信息）"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)

    class Meta:
        model = DockerRegistry
        fields = [
            'id', 'name', 'url', 'registry_type', 'auth_type', 'username',
            'is_active', 'is_default', 'connection_status',
            'repositories_count', 'last_sync_time', 'last_check_time', 'created_at', 'created_by_name'
        ]


class DockerStatisticsSerializer(serializers.Serializer):
    """Docker统计信息序列化器"""
    total_docker_servers = serializers.IntegerField()
    connected_servers = serializers.IntegerField()
    total_containers = serializers.IntegerField()
    running_containers = serializers.IntegerField()
    total_images = serializers.IntegerField()
    total_volumes = serializers.IntegerField()
    total_networks = serializers.IntegerField()
    total_registries = serializers.IntegerField()
    connected_registries = serializers.IntegerField()


class DockerContainerSerializer(serializers.Serializer):
    """Docker容器信息序列化器（动态数据，不存储到数据库）"""
    container_id = serializers.CharField()
    name = serializers.CharField()
    image = serializers.CharField()
    image_id = serializers.CharField()
    status = serializers.CharField()
    state = serializers.CharField()
    ports = serializers.ListField()
    mounts = serializers.ListField()
    networks = serializers.DictField()
    created = serializers.DateTimeField()
    started_at = serializers.DateTimeField(required=False, allow_null=True)
    finished_at = serializers.DateTimeField(required=False, allow_null=True)

    # 资源使用情况
    cpu_percent = serializers.FloatField(required=False, allow_null=True)
    memory_usage = serializers.IntegerField(required=False, allow_null=True)
    memory_limit = serializers.IntegerField(required=False, allow_null=True)
    memory_percent = serializers.FloatField(required=False, allow_null=True)
    network_rx = serializers.IntegerField(required=False, allow_null=True)
    network_tx = serializers.IntegerField(required=False, allow_null=True)
    block_read = serializers.IntegerField(required=False, allow_null=True)
    block_write = serializers.IntegerField(required=False, allow_null=True)


class DockerImageSerializer(serializers.Serializer):
    """Docker镜像信息序列化器（动态数据，不存储到数据库）"""
    image_id = serializers.CharField()
    repository = serializers.CharField()
    tag = serializers.CharField()
    digest = serializers.CharField(required=False, allow_blank=True)
    size = serializers.IntegerField()
    virtual_size = serializers.IntegerField()
    created = serializers.DateTimeField()
    labels = serializers.DictField(required=False)


class DockerNetworkSerializer(serializers.Serializer):
    """Docker网络信息序列化器（动态数据，不存储到数据库）"""
    network_id = serializers.CharField()
    name = serializers.CharField()
    driver = serializers.CharField()
    scope = serializers.CharField()
    subnet = serializers.CharField(required=False, allow_blank=True)
    gateway = serializers.CharField(required=False, allow_blank=True)
    ipam_config = serializers.DictField()
    containers = serializers.ListField()
    is_system = serializers.BooleanField()
    created = serializers.DateTimeField()


class DockerVolumeSerializer(serializers.Serializer):
    """Docker数据卷信息序列化器（动态数据，不存储到数据库）"""
    name = serializers.CharField()
    driver = serializers.CharField()
    mountpoint = serializers.CharField()
    options = serializers.DictField()
    labels = serializers.DictField()
    containers = serializers.ListField()
    created = serializers.DateTimeField()
    size = serializers.IntegerField(required=False, allow_null=True)


class DockerSystemInfoSerializer(serializers.Serializer):
    """Docker系统信息序列化器"""
    docker_version = serializers.CharField()
    api_version = serializers.CharField()
    kernel_version = serializers.CharField()
    operating_system = serializers.CharField()
    architecture = serializers.CharField()
    total_memory = serializers.IntegerField()
    containers = serializers.IntegerField()
    containers_running = serializers.IntegerField()
    containers_paused = serializers.IntegerField()
    containers_stopped = serializers.IntegerField()
    images = serializers.IntegerField()
    server_version = serializers.CharField()
    storage_driver = serializers.CharField()
    logging_driver = serializers.CharField()
    cgroup_driver = serializers.CharField()
    registry_config = serializers.DictField()


class DockerOperationSerializer(serializers.Serializer):
    """Docker操作序列化器"""
    operation = serializers.ChoiceField(choices=[
        ('start', '启动'),
        ('stop', '停止'),
        ('restart', '重启'),
        ('pause', '暂停'),
        ('unpause', '恢复'),
        ('remove', '删除'),
        ('kill', '强制停止'),
    ])
    container_id = serializers.CharField(required=False)
    image_id = serializers.CharField(required=False)
    network_id = serializers.CharField(required=False)
    volume_name = serializers.CharField(required=False)
    force = serializers.BooleanField(default=False)
    remove_volumes = serializers.BooleanField(default=False)
